from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, Float, JSON, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.core.database import Base

class ChatSession(Base):
    """聊天会话模型"""
    __tablename__ = "chat_sessions"
    
    id = Column(Integer, primary_key=True, index=True)
    session_id = Column(String(100), unique=True, index=True, nullable=False, comment="会话ID")
    dify_conversation_id = Column(String(100), nullable=True, comment="Dify会话ID")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")
    title = Column(String(200), nullable=True, comment="会话标题")
    status = Column(String(20), default="active", comment="会话状态")
    
    # 统计字段
    message_count = Column(Integer, default=0, comment="消息数量")
    total_tokens = Column(Integer, default=0, comment="总token数")
    satisfaction_score = Column(Float, nullable=True, comment="满意度评分")
    
    # 扩展字段
    meta_data = Column(JSON, nullable=True, comment="元数据")
    tags = Column(JSON, nullable=True, comment="标签")
    
    # 时间字段
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")
    last_message_at = Column(DateTime, nullable=True, comment="最后消息时间")
    
    # 关系
    user = relationship("User", back_populates="chat_sessions")
    messages = relationship("ChatMessage", back_populates="session", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<ChatSession(id={self.id}, session_id='{self.session_id}', user_id={self.user_id})>"

class ChatMessage(Base):
    """聊天消息模型"""
    __tablename__ = "chat_messages"
    
    id = Column(Integer, primary_key=True, index=True)
    message_id = Column(String(100), unique=True, index=True, nullable=False, comment="消息ID")
    session_id = Column(Integer, ForeignKey("chat_sessions.id"), nullable=False, comment="会话ID")
    
    # 消息内容
    role = Column(String(20), nullable=False, comment="角色(user/assistant/system)")
    content = Column(Text, nullable=False, comment="消息内容")
    content_type = Column(String(20), default="text", comment="内容类型")
    
    # AI相关字段
    model = Column(String(50), nullable=True, comment="使用的模型")
    tokens = Column(Integer, nullable=True, comment="token数量")
    response_time = Column(Float, nullable=True, comment="响应时间(秒)")
    
    # 评价字段
    rating = Column(Integer, nullable=True, comment="评分(1-5)")
    feedback = Column(Text, nullable=True, comment="反馈内容")
    
    # 扩展字段
    meta_data = Column(JSON, nullable=True, comment="元数据")
    
    # 时间字段
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    
    # 关系
    session = relationship("ChatSession", back_populates="messages")
    
    def __repr__(self):
        return f"<ChatMessage(id={self.id}, message_id='{self.message_id}', role='{self.role}')>"